package com.qf.zuul.fillter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: Song
 * @Date: 2022-03-21 10:11
 */
@Component
public class PermissFilter extends ZuulFilter {

    /**
     * 过滤器类型，权限判断一般是 pre
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     *  过滤器优先级
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     *  是否过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 核心的过滤逻辑写在这里
     * @return 这个方法虽然有返回值，但是这个返回值目前无所谓
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getParameter("token");
        if ("123".equals(token)) {
            //令牌合法，请求连接
            //不用做任何事
            return null;
        } else {
            //令牌不合法，请求被拦截
            //这里就不再进行请求转发了，直接从这里给浏览器返回数据即可
            RequestContext currentContext = RequestContext.getCurrentContext();
            currentContext.setResponseBody("forbidden:非法访问");
            //请求不再转发
            currentContext.setSendZuulResponse(false);
            //防止中文乱码
            currentContext.addZuulResponseHeader("content-type","text/html;charset=utf-8");
        }
        return null;
    }
}
